package com.lzy.business.task;

import com.lzy.common.apis.SmsSendServiceApi;
import com.lzy.common.dtos.SmsSendDto;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.tools.date.DateStyle;
import com.lzy.framework.tools.date.DateUtils;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.member.dtos.MemberUserDto;
import com.lzy.product.apis.AgentOrderInfoServiceApi;
import com.lzy.product.apis.AgentOrderYieldRatioServiceApi;
import com.lzy.product.apis.CouponProfitRecordServiceApi;
import com.lzy.product.apis.MemberCouponsServiceApi;
import com.lzy.product.constants.AgentOrderEnum;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.CouponProfitRecordDto;
import com.lzy.product.dtos.MemberCouponsDto;
import com.lzy.product.dtos.agent.AgentOrderInfoDto;
import com.lzy.product.dtos.agent.AgentOrderYieldRatioDto;
import com.lzy.sms.apis.UMengApi;
import com.lzy.sms.entity.UMengParam;
import com.lzy.sms.youMeng.base.AndroidNotification;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
/**
 * 代理商销售定时任务类
 */
public class AgentJob {

    @Autowired
    private AgentOrderYieldRatioServiceApi agentOrderYieldRatioServiceApi;

    @Autowired
    private CouponProfitRecordServiceApi couponProfitRecordServiceApi;

    @Autowired
    private MemberCouponsServiceApi memberCouponsServiceApi;

    @Autowired
    private AgentOrderInfoServiceApi agentOrderInfoServiceApi;

    @Autowired
    private MemberUserServiceApi memberUserServiceApi;

    @Autowired
    private SmsSendServiceApi smsSendServiceApi;

    @Value("${uMeng.Debug}")
    private Boolean uMenngDebug;

    @Autowired
    private UMengApi uMengApi;

    //通知声音
    private final static String SOUND = "unbelievable";
    //包名
    private final static String ACTIVITY = "com.lzhy.moneyhll.activity.me.myWallet.MyWalletActivity";

    private final Logger LOG = LoggerFactory.getLogger(AgentJob.class);

    /**
     * 代理商收益统计
     */
    @Scheduled(cron = "0 2 0 * * ? ")
    private void agencyIncomeStatistics() {
        LOG.info("代理商收益统计开始");
        Integer m = 0;
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        List<AgentOrderYieldRatioDto> agentOrderYieldRatioDtoList = agentOrderYieldRatioServiceApi.queryAgencyIncome();
        if (null != agentOrderYieldRatioDtoList) {
            for (AgentOrderYieldRatioDto agentOrderYieldRatioDto : agentOrderYieldRatioDtoList) {
                if (agentOrderYieldRatioDto.getDailyIncome() == null || agentOrderYieldRatioDto.getDailyIncome().equals("") || agentOrderYieldRatioDto.getDailyIncome().equals(0)) {
                    continue;
                }
                Ensure.that(DateUtils.isDate(agentOrderYieldRatioDto.getEndDate())).isTrue("01001616");
                Integer betweenDays = DateUtils.betweenDays(DateUtils.getNow(DateStyle.YYYY_MM_DD), agentOrderYieldRatioDto.getEndDate());
                //返现截止日期在今天之后  状态为返现中
                if (betweenDays > 0) {
                    agentOrderYieldRatioDto.setStatus(AgentOrderEnum.YieldRatioStatus.CashBack.getCode());
                } else if (betweenDays == 0) {
                    //返现截止日期在今天  状态为返现结束
                    agentOrderYieldRatioDto.setStatus(AgentOrderEnum.YieldRatioStatus.CashBackEnd.getCode());
                }
                Ensure.that(agentOrderYieldRatioServiceApi.update(agentOrderYieldRatioDto)).isTrue("01001614");
                AgentOrderInfoDto agentOrderInfoDto = agentOrderInfoServiceApi.queryOrderById(agentOrderYieldRatioDto.getOrderId());
                Ensure.that(agentOrderInfoDto).isNotNull("01001615");
                if (agentOrderYieldRatioDto.getStatus().equals(AgentOrderEnum.YieldRatioStatus.CashBack.getCode())) {
                    agentOrderInfoDto.setStatus(4);
                } else if (agentOrderYieldRatioDto.getStatus().equals(AgentOrderEnum.YieldRatioStatus.CashBackEnd.getCode())) {
                    agentOrderInfoDto.setStatus(5);
                }
                Ensure.that(agentOrderInfoServiceApi.updateAgentOrder(agentOrderInfoDto)).isTrue("01001625");
                CouponProfitRecordDto couponProfitRecordDto = new CouponProfitRecordDto();
                couponProfitRecordDto.setMemberId(agentOrderYieldRatioDto.getMemberId());
                couponProfitRecordDto.setOrderId(agentOrderYieldRatioDto.getOrderId());
                couponProfitRecordDto.setPhone(agentOrderInfoDto.getPhone());
                couponProfitRecordDto.setIncomeTime(DateUtils.getNow(DateStyle.YYYY_MM_DD_HH_MM_SS));
                couponProfitRecordDto.setAmount(agentOrderYieldRatioDto.getDailyIncome());
                //如果日期间隔大于限制提现天数 状态为可提现  否则为可限制
                if (betweenDays >= agentOrderYieldRatioDto.getLimitTime()) {
                    couponProfitRecordDto.setStatus(AgentOrderEnum.ProfitRecordStatus.CashWithdrawal.getCode());
                } else {
                    couponProfitRecordDto.setStatus(AgentOrderEnum.ProfitRecordStatus.Limit.getCode());
                }
                couponProfitRecordDto.setType(AgentOrderEnum.ProfitRecordType.AgentYield.getCode());
                couponProfitRecordDto.setLimitDay(agentOrderYieldRatioDto.getLimitTime());
                Ensure.that(couponProfitRecordServiceApi.insert(couponProfitRecordDto) > 0).isTrue("01001617");
                MemberCouponsDto memberCouponsDto = memberCouponsServiceApi.findByMemberIdAndType(couponProfitRecordDto.getMemberId(), 4);
                if (memberCouponsDto == null) {
                    LOG.info("会员龙币统计表数据不存在，新增");
                    MemberCouponsDto newMemberCouponsDto = new MemberCouponsDto();
                    newMemberCouponsDto.setMemberId(couponProfitRecordDto.getMemberId());
                    //newMemberCouponsDto.setDragonMoney(); 龙币金额
                    newMemberCouponsDto.setLimitedMoney(couponProfitRecordServiceApi.limitMoney(couponProfitRecordDto.getMemberId()));
                    newMemberCouponsDto.setType(4);
                    newMemberCouponsDto.setAvailableMoney(couponProfitRecordServiceApi.availableMoney(couponProfitRecordDto.getMemberId()));
                    Ensure.that(memberCouponsServiceApi.insert(newMemberCouponsDto) > 0).isTrue("01001618");
                } else {
                    LOG.info("会员龙币统计表数据存在，更新");
                    memberCouponsDto.setAvailableMoney(couponProfitRecordServiceApi.availableMoney(couponProfitRecordDto.getMemberId()));
                    memberCouponsDto.setLimitedMoney(couponProfitRecordServiceApi.limitMoney(couponProfitRecordDto.getMemberId()));
                    Ensure.that(memberCouponsServiceApi.update(memberCouponsDto)).isTrue("01001618");

                }
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                try {
                    MemberUserDto memberUserDto = memberUserServiceApi.selectMemberByMemberId(agentOrderYieldRatioDto.getMemberId());
                    if (memberCouponsDto == null) {
                        LOG.error("agentOrderYieldRatioDto id--》" + agentOrderYieldRatioDto.getId() + "||未查找到2.1对应用户");
                    } else {
                        SmsSendDto smsSendDto = new SmsSendDto();
                        smsSendDto.setPhone(memberUserDto.getAccount());
                        smsSendDto.setBusiType(AgentOrderEnum.smsType.agent_umeng.getValue());
                        smsSendDto.setNumber(agentOrderYieldRatioDto.getDailyIncome().toString());
                        smsSendDto.setStatus(0);
                        if (smsSendServiceApi.addSmsSend(smsSendDto)) {
                            m++;
                        }
                    }
                } catch (Exception e) {
                    LOG.error("agentOrderYieldRatioDto id--》" + agentOrderYieldRatioDto.getId() + "||失败" + e.getMessage());
                    e.printStackTrace();
                } finally {
                    DataSourceHolder.clearDataSource();
                }
            }
        }
        LOG.info("代理商收益统计结束  插入待发送数据" + m + "条");
    }

    /**
     * 推送
     */
    @Scheduled(cron = "0 0 10 * * ? ")
    private void push() {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        SmsSendDto smsSendDto = new SmsSendDto();
        smsSendDto.setBusiType(AgentOrderEnum.smsType.agent_umeng.getValue());
        smsSendDto.setStatus(0);
        List<SmsSendDto> smsSendDtoList = smsSendServiceApi.selectSmsSend(smsSendDto);
        for (SmsSendDto toBeSent : smsSendDtoList) {
            MemberUserDto memberUserDto = memberUserServiceApi.findMemberByMobile(toBeSent.getPhone());
            if (null != memberUserDto && memberUserDto.getDeviceType() != null && null != memberUserDto.getDeviceToken()) {
                UMengParam uMengParam = new UMengParam();
                uMengParam.setProductionMode(!uMenngDebug);
                uMengParam.setActivity(ACTIVITY);
                uMengParam.setAfterOpen(AndroidNotification.AfterOpenAction.go_activity.toString());
                uMengParam.setDeviceToken(memberUserDto.getDeviceToken());
                uMengParam.setDeviceType(memberUserDto.getDeviceType());
                uMengParam.setText("代理商分佣有" + toBeSent.getNumber() + "元到账了。请注意查收！");
                uMengParam.setTitle("龙之游消息");
                uMengParam.setTicker("代理商分佣有" + toBeSent.getNumber() + "元到账了。请注意查收！");
                uMengParam.setSound(SOUND);
                if (memberUserDto.getDeviceType().equals(2)) {
                    uMengParam.setSound(uMengParam.getSound() + ".caf");
                }
                uMengParam.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION.getValue());
                JSONObject result = uMengApi.unicast(uMengParam);
                //发送成功
                if (result.getString("ret").equals("SUCCESS")) {
                    toBeSent.setPhone(memberUserDto.getAccount());
                    toBeSent.setStatus(BusinessType.SendStatus.SEND.getCode());
                    toBeSent.setId(toBeSent.getId());
                    smsSendServiceApi.updateSmsSend(toBeSent);
                }
            }
        }
        DataSourceHolder.clearDataSource();
    }

}
